package com.example.lib_mvi.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

/**
 * @author yaotianxue
 * @description 懒加载：页面可见的时候加载数据
 * @date 2025/2/24
 */
abstract class BaseLazyLoadFragment:Fragment() {

    /**
     * 是否初始化过
     */
    protected var isInit = false
    /**
     * 是否已经完成加载
     */
    protected var isLoaded = false

    protected lateinit var mView: View

    /**
     * 创建view
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mView = getFragmentRootView(inflater,container,savedInstanceState)
        isInit = true
        prepareLoadData()
        initView()
        return mView
    }

    /**
     * view被创建好了
     */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initEnv()
        initEvent()
        initData()
    }

    /**
     * 销毁view
     */
    override fun onDestroyView() {
        super.onDestroyView()
        isInit = false
        isLoaded = false
    }

    private fun prepareLoadData(){
        if(!isInit) return
        if(userVisibleHint){ //可见
            lazyLoad()
            isLoaded = true
        }else{
            if(isLoaded){
                stopLoad()
            }
        }
    }
    /**
     * 延时加载
     */
    abstract fun lazyLoad()

    /**
     * 停止加载可以用于释放资源
     */
    protected fun stopLoad(){}


    protected open fun initEnv(){}
    protected open fun initEvent() {}

    protected open fun initData(){}

    protected open fun initView() {}
    /**
     * 获得fragment视图
     */
    abstract fun getFragmentRootView( inflater: LayoutInflater,
                                      container: ViewGroup?,
                                      savedInstanceState: Bundle?):View



    /**
     * 查找并获取资源
     */
    protected fun <T:View> findViewById(id:Int):T{
        return mView.findViewById(id)
    }


    /**
     * 显示提示消息
     */
    protected fun showMsg(msg: String?){
        if (activity is BaseActivity){
            (activity as BaseActivity).showMsg(msg?:"")
        }

    }






}